<?php

namespace services\api;


use common\enums\CacheEnum;
use Tinywan\Jwt\JwtToken;

/**
 * Class AccessTokenService
 * @package services\api
 * @author ycr <Email: yuncran@126.com>
 */
class AccessTokenService
{
    /**
     * 是否加入缓存
     *
     * @var bool
     */
    private $cache = false;


    /**
     * 获取 token
     * @param int $uid
     * @return array
     * @author ycr <Email: yuncran@126.com>
     */
    public function getAccessToken(int $uid)
    {
        return $token = JwtToken::generateToken(['id' => $uid]);
    }


    /**
     * 刷新令牌
     * @return array|string[]
     * @author ycr <Email: yuncran@126.com>
     */
    public function refreshToken()
    {
        return $token = JwtToken::refreshToken();
    }

    /**
     * 退出登录
     * @return bool
     * @author ycr <Email: yuncran@126.com>
     */
    public function logout()
    {
        return JwtToken::clear();
    }

    /**
     * 验证令牌
     * @param $token
     * @return array
     * @author ycr <Email: yuncran@126.com>
     */
    public function verifyToken($token)
    {
        $JwtToken = JwtToken::verify(true, $token);
        return $JwtToken;
    }

    /**
     * 缓存 access_token
     * @param $token
     * @return array
     * @author ycr <Email: yuncran@126.com>
     */
    public function getTokenToCache($token)
    {
        $key = $this->getCacheKey($token);
        $getToken = $this->getAccessToken($token);
        if ($this->cache === false) Yii()->redis::setEx($key, CacheEnum::APP_CACHE_TIME, $getToken);
        return $getToken;
    }


    /**
     * 禁用token
     * @param $access_token
     * @return bool
     * @author ycr <Email: yuncran@126.com>
     */
    public function disableByAccessToken($access_token)
    {
        return false;
    }


    /**
     * @param $access_token
     * @return string
     */
    protected function getCacheKey($access_token)
    {
        return CacheEnum::APP_API_ACCESS_TOKEN . $access_token;
    }


}